<?php
namespace Modules\Home\Services;

use Common\Models\UserModel;
use Common\Models\UserSeePointTreeModel;

class UserSeePointTreeService {
  public function getOne($user_id) {
    $findFirstUserSeePointTree = UserSeePointTreeModel::findFirst('user_id = ' . $user_id);
    if(!$findFirstUserSeePointTree) {
      return $this -> create(['user_id' => $user_id, 'promotion_user_ids' => $this -> __makeTree($user_id)]);
    }

    return ['code' => 0, 'user_see_point_tree' => $findFirstUserSeePointTree];
  }

  public function create($data) {
    $userSeePointTreeModel = new UserSeePointTreeModel($data);
    try {
      if(!$userSeePointTreeModel -> create()) {
        $messages = $userSeePointTreeModel -> getMessages();
        return ['code' => -1, 'message' => $messages[0] -> getMessage()];
      }
    } catch(\Exception $e) {
      return ['code' => -1, 'message' => $e -> getMessage()];
    }

    return ['code' => 0, 'user_see_point_tree' => $userSeePointTreeModel];
  }

  private function __makeTree($user_id) {
    $findFirstUser = UserModel::findFirst('user_id = ' . $user_id);
    if(!$findFirstUser) {
      return '';
    }

    $promotionUserIds = '';
    for($i=0;$i<20;$i++) {
      if($findFirstUser -> promotion_user_id == 0) {
        break;
      }

      $promotionUserIds .= $findFirstUser -> promotion_user_id . ',';

      $findFirstUser = UserModel::findFirst('user_id = ' . $findFirstUser -> promotion_user_id);
      if(!$findFirstUser) {
        break;
      }
    }

    return rtrim($promotionUserIds, ',');
  }
}
?>